package downstream

import (
	"context"
	"google.golang.org/grpc"
	"google.golang.org/grpc/status"
	"mall/api/open"
	"mall/internal/conf"
	"mall/internal/constant"
	"mall/pkg/ecode"
	"mall/pkg/log"
	"mall/pkg/network"
	"mall/pkg/request_key"
	"time"
)

func newOpenClient(ctx context.Context, addr string) (
	client open.OpenServiceClient, err error) {
	var conn *grpc.ClientConn
	conn, err = grpc.Dial(addr, grpc.WithInsecure(),
		grpc.WithUnaryInterceptor(network.ClientInterceptor(
			"bilin_open", time.Second*3, openErrorTranslator)))
	if err != nil {
		err = ecode.AppendMessage(constant.ErrRemoteError, "授权管理服务地址无法建立有效连接, err=%s", err.Error())
		log.FromContext(ctx).Warnw(err.Error())
		return
	}
	client = open.NewOpenServiceClient(conn)
	return
}

func openErrorTranslator(err error) (errCode *ecode.ErrorCode) {
	rpcStatus := status.Convert(err)
	errCode = ecode.AppendMessage(
		constant.ErrRemoteError, "授权管理服务调用失败，请稍后再试：%s", rpcStatus.Message())
	return
}

func (d *Downstream) GetWechatTemplates(ctx context.Context, appId string) (templateIds []string, err error) {
	if d.openClient == nil {
		if d.openClient, err = newOpenClient(
			ctx, conf.Conf.Downstream.OpenAddress); err != nil {
			return
		}
	}
	var reply *open.GetWechatPubTemplatesReply
	clientCtx, cancel := request_key.NewOutGoingContext(ctx, time.Second*3)
	defer cancel()
	if reply, err = d.openClient.GetWechatPubTemplates(
		clientCtx, &open.GetWechatPubTemplatesRequest{
			Domain: "inventory",
			AppId:  appId,
		}); err != nil {
		return
	}
	templateIds = reply.TemplateIds
	return
}

func (d *Downstream) SendWechatTemplate(ctx context.Context, memberId string, msgType, page, data string) (err error) {
	if d.openClient == nil {
		if d.openClient, err = newOpenClient(
			ctx, conf.Conf.Downstream.OpenAddress); err != nil {
			return
		}
	}
	// TODO 从会员服务使用memberId + scene 获取app_id & open_id
	clientCtx, cancel := request_key.NewOutGoingContext(ctx, time.Second*3)
	defer cancel()
	if _, err = d.openClient.SendWechatMiniPubMessage(clientCtx, &open.SendWechatMiniPubMessageRequest{
		AppId:   "",
		OpenId:  "",
		MsgType: msgType,
		Page:    page,
		Data:    data,
	}); err != nil {
		return
	}
	return
}

func (d *Downstream) GetWechatMiniLivingRoom(ctx context.Context, appId string) (roomId int64, err error) {
	if d.openClient == nil {
		if d.openClient, err = newOpenClient(
			ctx, conf.Conf.Downstream.OpenAddress); err != nil {
			return
		}
	}
	var reply *open.GetWechatMiniLivingRoomReply
	clientCtx, cancel := request_key.NewOutGoingContext(ctx, time.Second*3)
	defer cancel()
	if reply, err = d.openClient.GetWechatMiniLivingRoom(
		clientCtx, &open.GetWechatMiniLivingRoomRequest{
			AppId: appId,
		}); err != nil {
		return
	}
	roomId = reply.RoomId
	return
}
